﻿using Apps.BLL.Sys;
using Apps.Common;
using Apps.Core;
using Apps.DAL.Sys;
using Apps.Models;
using Apps.Models.Sys;
using System.IO;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Apps.WebApi.Core
{
    
   [JsonCallbackAttribute]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class BaseApiController : ApiController
    {

        protected virtual HttpRequestBase httpRequestBase
        {
            get {
                var context = (HttpContextBase)Request.Properties[ConfigPara.MS_HttpContext];
                return context.Request;
            }
        }
        /// <summary>
        /// 获取用户id
        /// </summary>
        /// <returns></returns>
        [HiddenApi]
        public string GetUserId()
        {
            var token = ContextRequest.GetQueryString(ConfigPara.Token);
           
            return LoginUserManage.DecryptToken(token);
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HiddenApi]
        public SysUserModel GetUser()
        {


            var content = Request.Properties[ConfigPara.MS_HttpContext] as HttpContextBase;
            var token = content.Request.Form[ConfigPara.Token];

            if (string.IsNullOrEmpty(token))
            {
                {
                    //获取请求数据  
                    Stream stream = HttpContext.Current.Request.InputStream;
                    string requestDataStr = "";
                    if (stream != null && stream.Length > 0)
                    {
                        stream.Position = 0; //当你读取完之后必须把stream的读取位置设为开始
                        using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
                        {
                            requestDataStr = reader.ReadToEnd().ToString();
                        }
                    }
                    if (requestDataStr != "")
                    {
                        dynamic obj = JsonHandler.Deserialize<dynamic>(requestDataStr);
                        token = obj.token;
                    }
                }

            }

            string userId = LoginUserManage.DecryptToken(token);
            SysUserModel model = new SysUserModel();

            if (!string.IsNullOrEmpty(userId))
            {

                SysUserBLL userBll = new SysUserBLL()
                {
                    m_Rep = new SysUserRepository(new DBContainer())
                };
                model =  userBll.GetById(userId);
            }
            return model;
        }

    }
}